//
//  UDPClient.swift
//  swifttest1
//
//  Created by kologe on 2024/9/16.
//

import Foundation
import Network

class UDPClient{
    var connection:NWConnection
    var message:String?
    var data:Data?
    
    
    init(host:String,port:UInt16){
        let nwEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(host), port: NWEndpoint.Port(rawValue: port)!)
        let nwParameters = NWParameters.udp
        nwParameters.allowLocalEndpointReuse = true
        self.connection = NWConnection(to: nwEndpoint, using: nwParameters)
        message = "udp hello"
    }
    
    func toBrocast(){
        let nwEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host("255.255.255.255"), port: NWEndpoint.Port(rawValue: 13532)!)
        let nwParameters = NWParameters.udp
        nwParameters.allowLocalEndpointReuse = true
        self.connection = NWConnection(to: nwEndpoint, using: nwParameters)
    }
    func start() {
            connection.stateUpdateHandler = { newState in
                switch newState {
                case .ready:
                    print("Connection ready")
                    self.sendMessage()
                case .failed(let error):
                    error_log("Connection failed: \(error)")
                default:
                    break
                }
            }
            connection.start(queue: .global())
        }
    
    func sendMessage() {
        var str = (String(data: self.data!, encoding: .utf8))
        if (self.data != nil) {
            connection.send(content: self.data, completion: .contentProcessed { error in
                if let error = error {
                    error_log("Failed to send data: \(error)")
                } else {
                    print("Data sent successfully")
                }
                self.close()
            })
            
        } else {
            print("Failed to convert message to Data")
        }
    }
    
    func close(){
        connection.cancel()
    }
    
}
